//
//  RAPGridImageCell.swift
//  COPYCAT-Weibo
//
//  Created by 闫萌 on 1/6/16.
//  Copyright © 2016 RendezvousAuParadis. All rights reserved.
//

import UIKit

@objc protocol RAPGridImageCellDelegate: NSObjectProtocol {
    optional func gridImageCell(GridImageCell: RAPGridImageCell, removeButtonDidClickAtIndexPath: NSIndexPath)
}

class RAPGridImageCell: UICollectionViewCell {
    
    // MARK: - 自定义属性
    var currentIndexPath: NSIndexPath?
    
    var image: UIImage? {
        didSet {
            if image == nil {
                imageView.image = UIImage(named: "compose_pic_add")
                /*
                注意，这里设置了hightlighted状态的图片，再复用时，
                要将其设置为nil
                */
                imageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
                removeButton.hidden = true
            } else {
                imageView.image = image
                imageView.highlightedImage = nil
                removeButton.hidden = false 
            }
        }
    }
    
    weak var delegate: RAPGridImageCellDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)

        prepareToUse()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func prepareToUse() {
        contentView.addSubview(imageView)
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
        contentView.addSubview(removeButton)
    }
    
    // MARK: - 懒加载控件
    private lazy var imageView: UIImageView = {
        let imageView = UIImageView()
        imageView.backgroundColor = UIColor.redColor()
        imageView.clipsToBounds = true
        imageView.contentMode = UIViewContentMode.ScaleAspectFill
        return imageView
    }()
    
    private lazy var removeButton: UIButton = {
        let removeButton = UIButton(title: nil, fontSize: 14, imageName: "compose_photo_close", backgroundImageName: nil, target: self, action: "removeButtonClicked:")
        return removeButton
    }()
    
    @objc private func removeButtonClicked(sender: UIButton) {
        /*
         对于可选的代理方法来说，添加❓即可起到判断有无的作用
        */
        delegate?.gridImageCell?(self, removeButtonDidClickAtIndexPath: self.currentIndexPath!)
        RAPLog("第\(self.currentIndexPath!.item)个被点击")
    }
    
    ///  排布子控件
    override func layoutSubviews() {
        removeButton.frame.origin = CGPointMake(bounds.width - removeButton.bounds.width, 0)
    }
}
